# check_server.py
import requests
import asyncio
import websockets
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def check_server_status():
    """检查服务器状态"""
    base_url = "http://localhost:8000"
    ws_url = "ws://localhost:8000"

    print("🔍 检查服务器状态...")

    # 检查 HTTP 服务
    try:
        response = requests.get(f"{base_url}/", timeout=5)
        if response.status_code == 200:
            print("✅ HTTP 服务器运行正常")
        else:
            print(f"❌ HTTP 服务器返回异常状态码: {response.status_code}")
    except requests.exceptions.ConnectionError:
        print("❌ 无法连接到 HTTP 服务器，请确保服务器正在运行")
        return False
    except Exception as e:
        print(f"❌ HTTP 检查失败: {e}")
        return False

    # 检查 WebSocket 服务
    try:
        async with websockets.connect(f"{ws_url}/ws/device/test_connection", timeout=5) as websocket:
            print("✅ WebSocket 服务器运行正常")
            return True
    except websockets.exceptions.InvalidURI:
        print("❌ WebSocket URL 格式错误")
    except websockets.exceptions.InvalidMessage:
        print("❌ WebSocket 消息格式错误")
    except asyncio.TimeoutError:
        print("❌ WebSocket 连接超时")
    except ConnectionRefusedError:
        print("❌ WebSocket 连接被拒绝，请检查服务器是否在端口 8000 运行")
    except Exception as e:
        print(f"❌ WebSocket 连接失败: {e}")

    return False


if __name__ == "__main__":
    asyncio.run(check_server_status())